package mani.multithreading;

import java.util.concurrent.Semaphore;

public class OddEvenSemaphoreTest implements Runnable  {
	private boolean isodd;
	int n;
	private static Semaphore od=new Semaphore(1); 
	private static Semaphore ev=new Semaphore(0); 
	
	OddEvenSemaphoreTest(boolean isodd,int n){
		this.isodd=isodd;
		this.n=n;
	}
	public void odd(int n) throws InterruptedException{
		int count=1;
		
		for(int i=0;i<n;i++){
			od.acquire(1);
			System.out.println("odd "+Thread.currentThread().getName()+" "+ count);
			count=count+2;
			ev.release(1);
			
			
		}
	}

	public void even(int n) throws InterruptedException{
		int count=2;
		
		for(int i=0;i<n;i++){
			ev.acquire(1);
			System.out.println("even "+Thread.currentThread().getName()+" "+ count);
			count=count+2;
			od.release(1);
			
			
		}
	}
	
	
	@Override
	public void run() {
		if(isodd){
			try {
				odd(n);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				even(n);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
	
public static void main(String[] args) {
	Thread odd=new Thread(new OddEvenSemaphoreTest(true, 10));
	Thread even=new Thread(new OddEvenSemaphoreTest(false, 10));
	
	even.start();odd.start();
	
		
	}


}
